package sf.r2dbc.handle;

import io.r2dbc.spi.Result;
import reactor.core.publisher.Flux;
import sf.r2dbc.rowmapper.R2dbcRowMapper;
import sf.r2dbc.sql.R2dbcResultSetCallback;

/**
 * 假分页
 * @param <T>
 */
public class R2dbcPageListHandler<T> implements R2dbcResultSetCallback<T> {

    private R2dbcRowMapper<T> mapper;
    private int first;
    private int max;

    public R2dbcPageListHandler(R2dbcRowMapper<T> mapper) {
        this.mapper = mapper;
    }

    @Override
    public Flux<T> callback(Flux<Result> resultFlux) {
        Flux<T> flux;
        if (first > 0) {
            flux = resultFlux.skip(first).flatMap(r -> r.map(mapper));
        } else {
            flux = resultFlux.flatMap(r -> r.map(mapper));
        }
        if (max > 0) {
            flux = flux.take(max);
        }
        return flux;
    }

    public void setFirstResult(int first) {
        this.first = first;
    }

    public void setMaxResults(int max) {
        this.max = max;
    }
}
